#!/usr/bin/env python
from __future__ import with_statement

import sys
import yaml
import pkg_resources
from shutil import copytree

from os import path, makedirs
from optparse import OptionParser

sys.path.append(path.abspath("."))

from igor.documents import Post, HomePage, Feed, Archive
from igor import version
from igor import tools
from igor import markup
from igor.config import Config
from igor.tools import init

parser = OptionParser(
    usage = "igor COMMAND [OPTIONS]",
    version = version,
    add_help_option = False,
    )

parser.add_option(
    '-h', '--help',            
    dest='help',               
    action='store_true',       
    help='Show help') 

_commands = {}

def register(name, cls):
    _commands[name] = cls

class Command(object):
    name = None
    usage = None

    def __init__(self):
        assert self.name
        assert self.usage

        self.parser = OptionParser(
            usage=self.usage,
            prog='%s %s' % (sys.argv[0], self.name),
            version=parser.version)

    def main(self, complete_args, args, initial_options):
        options, args = self.parser.parse_args(args)
        self.run(options, args)

class HelpCommand(Command):
    name = 'help'
    usage = '%prog'
    summary = 'Show available commands'

    def run(self, options, args):
        if args:
            command = args[0]
            if command not in _commands:
                raise Exception('No command with the name: %s' % command)

            command = _commands[command]
            command.parser.print_help()
            return

        parser.print_help()

        print('\nCommands available:')
        commands = list(set(_commands.values()))
        commands.sort(key=lambda x: x.name)
        for command in commands:
            print '  %s: %s' % (command.name, command.summary)
register(HelpCommand.name, HelpCommand)

class InitCommand(Command):
    name = "init"
    usage = "%prog [OPTIONS] INITIAL_REPOSITORY"
    summary = "Initialize a directory for use as an Igor project"

    def run(self, options, args):
        if not args:
            print(self.usage)

        out_path = path.abspath(path.expanduser(args[0]))

        if path.exists(out_path):
            print("Directory %s already exists" % out_path)
            sys.exit(1)

        print("Initializing new igor project: %s" % out_path)
        init(out_path)

register(InitCommand.name, InitCommand)

class PublishCommand(Command):
    name = "publish"
    usage = "%prog [OPTIONS] PROJECT_DIRECTORY [OUTPUT_DIRECTORY]"
    summary = "Publish a site given an igor repository"

    def run(self, options, args):
        if not args:
            print(self.usage)

        source = args[0]
        destination = ""

        if len(args) >= 2:
            destination  = args[1]
        tools.publish(source, destination)
register(PublishCommand.name, PublishCommand)


def main(initial_args = None):
    if initial_args is None:
        initial_args = sys.argv[1:]

    options, args = parser.parse_args(initial_args)

    if options.help and not args:
        args = ['help']

    command = args[0].lower()

    if command not in _commands:
        parser.error("No command by the name")

    command = _commands[command]()
    return command.main(initial_args, args[1:], options)
        
if __name__ == "__main__":
    main()
